package com.online.olsrootserver.controller;

import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.kefu.WxMpKefuMessage;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by littleheng on 2018/4/26
 */
@RestController
public class WxInterfaceProvideController {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());


    @Autowired
    private WxMpService wxService;

    /**
     * 发送文本消息
     * @return
     */
    @RequestMapping(value = "/sendText", method = RequestMethod.POST)
    public Map sendTextInfo(@RequestBody Map map) {

        String openId = map.get("open_id").toString();
        String content = map.get("content").toString();

        WxMpKefuMessage message = null;
        if (!"".equals(openId)) {
            message = new WxMpKefuMessage();
            message.setMsgType(WxConsts.KefuMsgType.TEXT);
            message.setToUser(openId);
            message.setContent(content);
        }
        return this.sendKefuMessage(message);
    }

    /**
     * 发送图片消息
     * @return
     */
    @RequestMapping(value = "/sendImage", method = RequestMethod.POST)
    public Map sendImageInfo(@RequestBody Map map) {
        String openId = map.get("open_id").toString();
        String mediaId = map.get("media_id").toString();

        WxMpKefuMessage message = null;
        if (!"".equals(openId) && !"".equals(mediaId)) {
            message = new WxMpKefuMessage();
            message.setMsgType(WxConsts.KefuMsgType.IMAGE);
            message.setToUser(openId);
            message.setMediaId(mediaId);
        }
        return this.sendKefuMessage(message);
    }

    /**
     * 发送语音消息
     * @param openId
     * @param mediaId
     * @return
     */
    @RequestMapping(value = "/sendVoice", method = RequestMethod.GET)
    public Map sendVoiceInfo(@RequestParam("open_id")String openId,
                                @RequestParam("media_id")String mediaId) {
        WxMpKefuMessage message = new WxMpKefuMessage();
        message.setToUser(openId);
        message.setMsgType(WxConsts.KefuMsgType.VOICE);
        message.setMediaId(mediaId);
        return this.sendKefuMessage(message);
    }

    /**
     * 发送视频消息
     * @param openId
     * @param mediaId
     * @param title
     * @param thumbMediaId
     * @param description
     * @return
     */
    @RequestMapping(value = "/sendVideo", method = RequestMethod.GET)
    public Map sendVideoInfo(@RequestParam("open_id")String openId,
                                @RequestParam("media_id")String mediaId,
                                @RequestParam("title")String title,
                                @RequestParam("thumb_media_id")String thumbMediaId,
                                @RequestParam("description")String description) {
        WxMpKefuMessage message = new WxMpKefuMessage();
        message.setToUser(openId);
        message.setMsgType(WxConsts.KefuMsgType.VIDEO);
        message.setTitle(title);
        message.setMediaId(mediaId);
        message.setThumbMediaId(thumbMediaId);
        message.setDescription(description);
        return this.sendKefuMessage(message);
    }

    /**
     * 发送音乐消息
     * @param openId
     * @param title
     * @param thumbMediaId
     * @param description
     * @param musicUrl
     * @param hqMusicUrl
     * @return
     */
    @RequestMapping(value = "/sendMusic", method = RequestMethod.GET)
    public Map sendMusicInfo(@RequestParam("open_id")String openId,
                                @RequestParam("title")String title,
                                @RequestParam("thumb_media_id")String thumbMediaId,
                                @RequestParam("description")String description,
                                @RequestParam("music_url")String musicUrl,
                                @RequestParam("hq_music_url")String hqMusicUrl) {
        WxMpKefuMessage message = new WxMpKefuMessage();
        message.setToUser(openId);
        message.setTitle(title);
        message.setThumbMediaId(thumbMediaId);
        message.setMsgType(WxConsts.KefuMsgType.MUSIC);
        message.setDescription(description);
        message.setMusicUrl(musicUrl);
        message.setHqMusicUrl(hqMusicUrl);
        return this.sendKefuMessage(message);
    }

    /**
     * 发送图文消息
     * @param openId
     * @param articles
     * @return
     */
    @RequestMapping(value = "/sendNews", method = RequestMethod.GET)
    public Map sendNewsInfo(@RequestParam("open_id")String openId,
                                @RequestParam("articles")String articles) {

        List<WxMpKefuMessage.WxArticle> articleList = new ArrayList<WxMpKefuMessage.WxArticle>();
        JSONArray jsonArr = JSONArray.fromObject(articles);
        for (int i = 0; i < jsonArr.size(); i++) {
            JSONObject jsonObj = jsonArr.getJSONObject(i);
            String url = jsonObj.getString("url");
            String picUrl = jsonObj.getString("pic_url");
            String title = jsonObj.getString("title");
            String description = jsonObj.optString("description");

            WxMpKefuMessage.WxArticle article = new WxMpKefuMessage.WxArticle();
            article.setUrl(url);
            article.setPicUrl(picUrl);
            article.setTitle(title);
            article.setDescription(description);

            articleList.add(article);

        }

        WxMpKefuMessage message = new WxMpKefuMessage();
        message.setMsgType(WxConsts.KefuMsgType.NEWS);
        message.setToUser(openId);
        message.setArticles(articleList);
        return this.sendKefuMessage(message);
    }

//    /**
//     * 新增临时素材
//     * @param mediaType 媒体文件类型：图片(image)、语音(voice)、视频(video)、缩略图(thumb)
//     * @return
//     */
//    @RequestMapping(value = "/mediaUpload", method = RequestMethod.POST)
//    public Map mediaUpload(@RequestBody Map map) {
//
//        String mediaType = map.get("mediaType").toString();
//        File file = new File(map.get("file").toString());
//
//        WxMediaUploadResult res = null;
//        try {
//            res = this.wxService.getMaterialService()
//                    .mediaUpload(mediaType, file);
//        } catch (Exception e) {
//            this.logger.info(e.getMessage(), e);
//        }
//
//        Map<String, Object> maps = new HashMap<>();
//        maps.put("result", res != null ? "0" : "1");
//        maps.put("type", res != null ? res.getType() : "" );
//        maps.put("media_id", res != null ? res.getMediaId(): "");
//        maps.put("created_at", res != null ? res.getCreatedAt() : 0);
//        maps.put("thumb_media_id", res != null ? res.getThumbMediaId() : "" );
//
//        return maps;
//    }
//
//    /**
//     * 获取临时素材
//     * @param mediaId 媒体id
//     * @return
//     */
//    @RequestMapping(value = "/mediaDownload", method = RequestMethod.POST)
//    public Map mediaDownload(@RequestBody Map map) {
//        String mediaId = map.get("mediaId").toString();
//
//        Map<String, Object> maps = new HashMap<String, Object>();
//        File file = null;
//        try {
//            file = this.wxService.getMaterialService().mediaDownload(mediaId);
//            maps.put("result", "0");
//            maps.put("file", file);
//        } catch (Exception e) {
//            maps.put("result", "1");
//            this.logger.info(e.getMessage(), e);
//        }
//        return maps;
//    }

    private Map sendKefuMessage(WxMpKefuMessage wxMpKefuMessage) {
        boolean result = false;
        try {
            result = this.wxService.getKefuService().sendKefuMessage(wxMpKefuMessage);
        } catch(Exception e) {
            this.logger.info(e.getMessage(), e);
        }
        Map<String, Integer> map = new HashMap<>();
        map.put("result", result == true ? 0 : 1);
        return map;
    }
}